package com.huxiu.yd;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.Comment;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.CommentsResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.AvatarView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/21:上午9:27.
 */
public class ReviewListActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        OnRefreshListener2<ListView> {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(R.id.send_button)
    TextView sendButton;

    @InjectView(R.id.review_edit)
    EditText reviewEdit;

    private String id;

    private int type;

    private static final int TYPE_DISCOVERY = 0;

    private static final int TYPE_SPARE = 1;

    private View mEmptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review_list);
        ButterKnife.inject(this);
        if (getIntent().hasExtra(Constants.ARTICLE_ID_KEY)) {
            type = TYPE_DISCOVERY;
            id = getIntent().getStringExtra(Constants.ARTICLE_ID_KEY);
        } else if (getIntent().hasExtra(Constants.SPARE_ID_KEY)) {
            type = TYPE_SPARE;
            id = getIntent().getStringExtra(Constants.SPARE_ID_KEY);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText(R.string.comments);
        adapter = new CommentsAdapter();
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        list.setOnRefreshListener(this);
        list.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        mEmptyView = findViewById(R.id.empty);
        sendButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                submitComment();
            }
        });
    }

    private void submitComment() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "add_comment");
        params.put("article_id", id);
        params.put("comment", reviewEdit.getText().toString());
        GsonRequest<BaseResponse> request = new GsonRequest<>(type == TYPE_DISCOVERY ?
                NetworkConstants.DISCOVERY_URL : NetworkConstants.GOODS_URL,
                Method.POST, BaseResponse.class, true, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    Utils.showToast(R.string.submit_comment_success);
                    reviewEdit.setText("");
                    getComments(0);
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private int currentPage = 0;


    private void getComments(final int page) {
        boolean isDiscovery = type == TYPE_DISCOVERY;
        String url = isDiscovery ? NetworkConstants.DISCOVERY_URL
                : NetworkConstants.GOODS_URL;
        String idKey = isDiscovery ? "article_id" : "user_goods_id";
        String act = "comment";
        Map<String, String> params = new HashMap<>();
        params.put(idKey, id);
        params.put("act", act);
        params.put("page", Integer.toString(page));
        GsonRequest<CommentsResponse> request = new GsonRequest<>(url, Method.POST,
                CommentsResponse.class, false, params, new Listener<CommentsResponse>() {
            @Override
            public void onResponse(CommentsResponse response) {
                if (response.isSuccess()) {
                    if (page == 0) {
                        comments.clear();
                    }
                    Collections.addAll(comments, response.data);
                    adapter.notifyDataSetChanged();
                    currentPage = response.page;
                    setEmptyView();
                }
                refreshComplete();
            }
        }, mErrorListener);
        mQueue.add(request);
    }

    private void setEmptyView() {
        if (adapter.isEmpty()) {
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgress();
            Throwable t = error.getCause();
            if (t instanceof ErrorResponseException) {
//                Utils.showToast(error.getMessage());
            } else {
                Utils.showToast(R.string.generic_failure);
            }
            refreshComplete();
            setEmptyView();
        }
    };

    List<Comment> comments = new ArrayList<>();

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
    }

    private CommentsAdapter adapter;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Comment comment = adapter.getItem(position - 1);
        Intent intent = new Intent(this, CommentActivity.class);
        intent.putExtra("comment", comment);
        intent.putExtra("is_discovery", type);
        startActivity(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getComments(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getComments(currentPage + 1);
    }

    private class CommentsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return comments.size();
        }

        @Override
        public Comment getItem(int position) {
            return comments.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder vh;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.review_list_item, parent, false);
                vh = new ViewHolder(view);
                view.setTag(vh);
            }
            final Comment comment = getItem(position);
            vh = (ViewHolder) view.getTag();
            vh.avatar.setUserInfo(comment.user_id, comment.avatar, comment.name);
            vh.name.setText(comment.name);
            vh.name.setCompoundDrawablesWithIntrinsicBounds(0, 0, comment
                    .getUserDrawable(), 0);
            vh.time.setText(Utils.getDateString(comment.create_time));
            vh.content.setText(comment.content);
            vh.dianpingCount.setText(Integer.toString(comment.recommend_num));
            final AvatarView avatar = vh.avatar;
            vh.name.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    avatar.performClick();
                }
            });
            vh.content.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ReviewListActivity.this, CommentActivity.class);
                    intent.putExtra("comment", comment);
                    intent.putExtra("show_keyboard", true);
                    startActivity(intent);
                }
            });
            if (comment.recommend_num > 0) {
                vh.dianpingCount.setText(Integer.toString(comment.recommend_num));
                vh.dianpingCount.setVisibility(View.VISIBLE);
            } else {
                vh.dianpingCount.setVisibility(View.GONE);
            }
            return view;
        }
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'review_list_item.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers
     *         (http://github.com/avast)
     */
    static class ViewHolder {

        @InjectView(R.id.avatar)
        AvatarView avatar;

        @InjectView(R.id.name)
        TextView name;

        @InjectView(R.id.time)
        TextView time;

        @InjectView(R.id.content)
        TextView content;

        @InjectView(R.id.dianping_count)
        TextView dianpingCount;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}
